//
//  KABHomepageVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/15.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABHomepageVC.h"
#import "KABCosplayTCell.h"
#import "KABHpUserWallVC.h"
#import "KABApplyCelebrityVC.h"
#import "KABHpEditInforVC.h"
#import "KABThemeMallVC.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "GlobalHeader.h"
#import "KABCosplayDetailVC.h"
#import <YYWebImage.h>
#import "UIColor+XDHex.h"
#import <TZImagePickerController.h>
#import <TZImageManager.h>
#import "XDQiniuManager.h"
#import "KSPhotoBrowser.h"
#import "KABMineColCosVC.h"
#import "KABHpAlbumVC.h"

@interface KABHomepageVC ()<UITableViewDelegate, UITableViewDataSource, KABCosplayTCellDelegate, TZImagePickerControllerDelegate>

@property (strong, nonatomic) IBOutlet UIView *headerBgView;
@property (weak, nonatomic) IBOutlet UIImageView *skinImgView;
@property (weak, nonatomic) IBOutlet UIImageView *portraitImgView;
@property (weak, nonatomic) IBOutlet UIButton *changePorBtn;
@property (weak, nonatomic) IBOutlet UIButton *changeBgImgBtn;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIButton *editInfoBtn;
@property (weak, nonatomic) IBOutlet UILabel *autographLabel;
@property (weak, nonatomic) IBOutlet UIButton *celebrityBtn;
@property (weak, nonatomic) IBOutlet UIButton *followBtn;
@property (weak, nonatomic) IBOutlet UIButton *fansBtn;
@property (weak, nonatomic) IBOutlet UIButton *albumBtn;

@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) UIBarButtonItem *followBarBtnItem;
@property (strong, nonatomic) UIBarButtonItem *skinBarBtnItem;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (strong, nonatomic) KABMineHomepage *hpModel;

@end

static NSString *const kReuseCellId = @"KABCosplayTCell";
static NSInteger const kRequestCosplaySize = 20;

@implementation KABHomepageVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = self.user_name;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
    
    if (self.user_id == [KABModel sharedInstance].userInfo.uid) {
        self.navigationItem.rightBarButtonItem = self.skinBarBtnItem;
    } else {
        self.navigationItem.rightBarButtonItem = self.followBarBtnItem;
    }
}

- (void)initSubViews {
    UITapGestureRecognizer *skinTapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(skinImgViewTapped:)];
    [self.skinImgView addGestureRecognizer:skinTapGesture];
    self.portraitImgView.layer.masksToBounds = YES;
    self.portraitImgView.layer.cornerRadius = CGRectGetWidth(self.portraitImgView.bounds) / 2.0;
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(portraitImgViewTapped:)];
    [self.portraitImgView addGestureRecognizer:tapGesture];
    
    self.changePorBtn.layer.masksToBounds = YES;
    self.changePorBtn.layer.cornerRadius = CGRectGetWidth(self.changePorBtn.bounds) / 2.0;
    [self.changePorBtn addTarget:self action:@selector(changePorBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.changeBgImgBtn.layer.masksToBounds = YES;
    self.changeBgImgBtn.layer.cornerRadius = 4;
    [self.changeBgImgBtn addTarget:self action:@selector(changeBgImgBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.editInfoBtn addTarget:self action:@selector(editInfoBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [self.celebrityBtn addTarget:self action:@selector(celebrityBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.followBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.followBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.followBtn setTitle:@"18\n粉丝" forState:UIControlStateNormal];
    [self.followBtn addTarget:self action:@selector(followBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.fansBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.fansBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.fansBtn setTitle:@"18\n粉丝" forState:UIControlStateNormal];
    [self.fansBtn addTarget:self action:@selector(fansBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    self.albumBtn.titleLabel.lineBreakMode = NSLineBreakByWordWrapping;
    self.albumBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [self.albumBtn setTitle:@"0\n相册" forState:UIControlStateNormal];
    [self.albumBtn addTarget:self action:@selector(albumBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat screenWidth = CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat headerHeight = screenWidth * 3.0 / 5.0 + 160.0;
    self.headerBgView.frame = CGRectMake(0, 0, screenWidth, headerHeight);
    self.tableView.tableHeaderView = self.headerBgView;
    
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 448.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.hpModel.cosplay_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABCosplayTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.hpModel.cosplay_list.count) {
        BOOL showDel = (self.hpModel.user_detail.user_id == [KABModel sharedInstance].userInfo.uid);
        [cell configViewWithCosplayItem:self.hpModel.cosplay_list[indexPath.section] showDeleteBtn:showDel showPullDownBtn:NO];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 5.9;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.1;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosItem = self.hpModel.cosplay_list[indexPath.section];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - KABCosplayTCellDelegate
- (void)kABCosplayTCell:(KABCosplayTCell *)cell portraitImgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:imgView
                                                    imageUrl:[NSURL URLWithString:self.hpModel.cosplay_list[indexPath.section].publisher_imageurl]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell praiseBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.hpModel.cosplay_list[indexPath.section];
    item.is_praise = !item.is_praise;
    item.is_praise ? ++item.praise : --item.praise;
    
    // 请求服务器
    [self requestCosPraiseWithCosId:item.cosplayId isPraise:item.is_praise];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell commentBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosItem = self.hpModel.cosplay_list[indexPath.section];
    //    detailVC.scrollToComment = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell collectBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.hpModel.cosplay_list[indexPath.section];
    item.is_collected = !item.is_collected;
    
    // 请求服务器
    [self requestCosCollectWithCosId:item.cosplayId isCollected:item.is_collected];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell deleteBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.hpModel.cosplay_list[indexPath.section];
    
    // 请求服务器
    [self requestCosDeleteWithCosId:item.cosplayId successHandle:^{
        [self.hpModel removeCosListItem:item];
        // 更新界面
        [self.tableView beginUpdates];
        [self.tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
        [self.tableView endUpdates];
    }];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell linkTapped:(NSURL *)url {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.hpModel.cosplay_list[indexPath.section];
    
    if ([url isKindOfClass:[NSURL class]]) {
        NSInteger index = [url.absoluteString integerValue];
        NSArray *linkStrArray = item.topContentTopicAndAtUserArray;
        if (index < linkStrArray.count) {
            NSString *linkStr = linkStrArray[index];
            if (linkStr.length <= 2) {
                return;
            }
            if ([linkStr hasPrefix:@"#"]) {
                KABMineColCosVC *vc = [[KABMineColCosVC alloc] init];
                vc.viewType = KABMineColCosVCTypeTopicList;
                vc.topicStr = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            } else if([linkStr hasPrefix:@"@"]) {
                KABHomepageVC *vc = [[KABHomepageVC alloc] init];
                vc.user_name = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            }
        }
    }
}

#pragma mark - event response
- (void)skinBtnTapped:(UIBarButtonItem *)barBtn {
    KABThemeMallVC *vc = [[KABThemeMallVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)blacklistBtnTapped:(UIBarButtonItem *)barBtn {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"加入黑名单" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        [self sureToAddBlackList];
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)followBarBtnItemTapped:(UIBarButtonItem *)barBtn {
    if (!self.hpModel) {
        return;
    }
    BOOL is_follow = (self.hpModel.follow_state & 0x01);
    [self requestFollowWithFollowerId:self.hpModel.user_detail.user_id isFollow:!is_follow];
}
- (void)editInfoBtnTapped:(UIBarButtonItem *)barBtn {
    KABHpEditInforVC *vc = [[KABHpEditInforVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)celebrityBtnTapped:(UIButton *)btn {
//    KABApplyCelebrityVC *vc = [[KABApplyCelebrityVC alloc] init];
//    [self.navigationController pushViewController:vc animated:YES];
}
- (void)skinImgViewTapped:(UIGestureRecognizer *)gesture {
    NSString *homepageImgUrlStr = self.hpModel.user_detail.homepage_img_url ? self.hpModel.user_detail.homepage_img_url : @"";
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:(UIImageView *)gesture.view
                                                    imageUrl:[NSURL URLWithString:homepageImgUrlStr]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}
- (void)portraitImgViewTapped:(UIGestureRecognizer *)gesture {
    KSPhotoItem *photoItem = [KSPhotoItem itemWithSourceView:(UIImageView *)gesture.view
                                                    imageUrl:[NSURL URLWithString:self.hpModel.user_detail.headimg_url]];
    KSPhotoBrowser *browser = [KSPhotoBrowser browserWithPhotoItems:@[photoItem] selectedIndex:0];
    browser.dismissalStyle = KSPhotoBrowserInteractiveDismissalStyleNone;
    browser.backgroundStyle = KSPhotoBrowserBackgroundStyleBlack;
    browser.loadingStyle = KSPhotoBrowserImageLoadingStyleDeterminate;
    browser.pageindicatorStyle = KSPhotoBrowserPageIndicatorStyleDot;
    browser.bounces = NO;
    [browser showFromViewController:self];
}
- (void)changePorBtnTapped:(UIButton *)btn {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count) {
            [self uploadImageToQiniuWithHeaderImg:photos.firstObject homepageImg:nil];
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)changeBgImgBtnTapped:(UIButton *)btn {
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
    CGFloat width =  CGRectGetWidth([UIScreen mainScreen].bounds);
    CGFloat screenHeight = CGRectGetHeight([UIScreen mainScreen].bounds);
    imagePickerVc.cropRect = CGRectMake(0, screenHeight / 2.0 - width * 0.3, width, width * 0.6);
    // You can get the photos by block, the same as by delegate.
    // 你可以通过block或者代理，来得到用户选择的照片.
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        if (photos.count) {
            [self uploadImageToQiniuWithHeaderImg:nil homepageImg:photos.firstObject];
        }
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
- (void)followBtnTapped:(UIButton *)btn {
    KABHpUserWallVC *vc = [[KABHpUserWallVC alloc] initWithViewType:KABHpUserWallVCFollow];
    vc.user_id = self.hpModel.user_detail.user_id;
    vc.user_name = self.hpModel.user_detail.nick_name;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)fansBtnTapped:(UIButton *)btn {
    KABHpUserWallVC *vc = [[KABHpUserWallVC alloc] initWithViewType:KABHpUserWallVCFans];
    vc.user_id = self.hpModel.user_detail.user_id;
    vc.user_name = self.hpModel.user_detail.nick_name;
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)albumBtnTapped:(UIButton *)btn {
    KABHpAlbumVC *vc = [[KABHpAlbumVC alloc] init];
    vc.user_id = self.hpModel.user_detail.user_id;
    vc.user_name = self.hpModel.user_detail.nick_name;
    [self showViewController:vc sender:nil];
}

#pragma mark - private methods
- (void)sureToAddBlackList {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"确定将该用户加入黑名单吗？" message:@"加入黑名单后，首页将自动屏蔽TA发布的内容" preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self requestAddBlacklist];
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.hpModel.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    self.navigationItem.title = self.hpModel.user_detail.nick_name;
    self.followBarBtnItem.image = (self.hpModel.follow_state & 0x01) ? [UIImage imageNamed:@"cosplay_praise_sel"] : [UIImage imageNamed:@"cosplay_praise"];
    BOOL isMyselfHp = self.hpModel.user_detail.user_id == [KABModel sharedInstance].userInfo.uid;
    if (isMyselfHp) {
        self.navigationItem.rightBarButtonItem = self.skinBarBtnItem;
    } else {
        self.navigationItem.rightBarButtonItem = self.followBarBtnItem;
    }
    
    self.editInfoBtn.hidden = !isMyselfHp;
    self.changePorBtn.hidden = !isMyselfHp;
    self.changeBgImgBtn.hidden = !isMyselfHp;
    
    [self.skinImgView yy_setImageWithURL:[NSURL URLWithString:self.hpModel.user_detail.homepage_img_url] placeholder:[KABDefaultVarModel sharedInstance].skinDefaultImg];
    [self.portraitImgView yy_setImageWithURL:[NSURL URLWithString:self.hpModel.user_detail.headimg_url] placeholder:[KABDefaultVarModel sharedInstance].smallDefaultImg];
    self.nameLabel.text = self.hpModel.user_detail.nick_name;
    self.autographLabel.text = self.hpModel.user_detail.sign;
    if (self.hpModel.user_detail.is_celebrity) {
        UIImage *image = nil;
        NSString *rankStr = nil;
        if (self.hpModel.user_detail.ranking_id <= 1000) {
            image = [UIImage imageNamed:@"cosplay_activity_gold"];
            rankStr = [NSString stringWithFormat:@"%zd", self.hpModel.user_detail.ranking_id];
        }else if (self.hpModel.user_detail.ranking_id <= 5000) {
            image = [UIImage imageNamed:@"cosplay_activity_silver"];
        } else {
            image = [UIImage imageNamed:@"cosplay_activity_bronze"];
        }
        [self.celebrityBtn setBackgroundImage:image forState:UIControlStateNormal];
        [self.celebrityBtn setTitle:rankStr forState:UIControlStateNormal];
        self.celebrityBtn.hidden = NO;
    } else {
        self.celebrityBtn.hidden = YES;
    }
    
    NSDictionary *attrsDic = @{NSForegroundColorAttributeName : [UIColor xd_colorWithHex:KABGlobalColorSettingFont],
                          NSFontAttributeName : [UIFont systemFontOfSize:12.0]};
    {
        NSString *totalFollowStr = [NSString stringWithFormat:@"%zd", self.hpModel.user_detail.total_follow];
        NSString *followStr = [NSString stringWithFormat:@"%@\n关注", totalFollowStr];
        NSMutableAttributedString *mAStr = [[NSMutableAttributedString alloc] initWithString:followStr];
        [mAStr addAttributes:attrsDic range:NSMakeRange(totalFollowStr.length, followStr.length - totalFollowStr.length)];
        [self.followBtn setAttributedTitle:mAStr forState:UIControlStateNormal];
    }
    
    {
        NSString *totalFansStr = [NSString stringWithFormat:@"%zd", self.hpModel.user_detail.total_fans];
        NSString *fansStr = [NSString stringWithFormat:@"%@\n粉丝", totalFansStr];
        NSMutableAttributedString *mFansAStr = [[NSMutableAttributedString alloc] initWithString:fansStr];
        [mFansAStr addAttributes:attrsDic range:NSMakeRange(totalFansStr.length, fansStr.length - totalFansStr.length)];
        [self.fansBtn setAttributedTitle:mFansAStr forState:UIControlStateNormal];
    }
    
    {
        NSString *totalAlbumStr = [NSString stringWithFormat:@"%zd", self.hpModel.total_photo];
        NSString *albumStr = [NSString stringWithFormat:@"%@\n相册", totalAlbumStr];
        NSMutableAttributedString *mAlbumAStr = [[NSMutableAttributedString alloc] initWithString:albumStr];
        [mAlbumAStr addAttributes:attrsDic range:NSMakeRange(totalAlbumStr.length, albumStr.length - totalAlbumStr.length)];
        [self.albumBtn setAttributedTitle:mAlbumAStr forState:UIControlStateNormal];
    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    [self requestHomepageWithHeader:isHeader];
}

- (KABMineHomepage *)homepageWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.hpModel;
    }
    
    KABMineHomepage *temp = [KABMineHomepage yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.hpModel;
    }
    
    if (AddMore && self.hpModel) {
        [self.hpModel addMoreWithData:temp];
    } else {
        self.hpModel = temp;
    }
    return self.hpModel;
}

- (void)uploadImageToQiniuWithHeaderImg:(UIImage *)headerImage homepageImg:(UIImage *)homepageImage {
    if ((!headerImage) && (!homepageImage)) {
        return;
    }
    
    NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:2];
    if (headerImage) {
        [mArray addObject:headerImage];
    }
    if (homepageImage) {
        [mArray addObject:homepageImage];
    }
    
    // 上传图片
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    hud.mode = MBProgressHUDModeAnnularDeterminate;
    hud.progress = 0;
    hud.label.text = @"上传图片...";
    [[XDQiniuManager sharedInstance] uploadImages:mArray progress:^(NSString *key, float percent) {
        dispatch_async(dispatch_get_main_queue(), ^{
            hud.progress = percent;
        });
    } success:^(NSArray<NSString *> *urlArray) {
        [hud hideAnimated:NO];
        // 发表到服务器
        NSString *headerImgUrl = headerImage ? urlArray.firstObject : nil;
        NSString *homepageUrl  = homepageImage ? urlArray.lastObject : nil;
        [self requestEditUserInfoWithHeadImgUrl:headerImgUrl homepage_img_url:homepageUrl];
        NSLog(@"开始发表到服务器");
    } failure:^(NSString *error) {
        NSLog(@"上传图片失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:error];
    }];
}

#pragma mark - network request
- (void)requestCosDeleteWithCosId:(NSInteger)cosId successHandle:(void(^)(void))success {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId)};
    NSLog(@"删除的请求%@", pars);
    [[XDAFNetworking sharedInstance] DELETE:[ApiManager apiCosplay] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay删除返回：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            if (success) {
                success();
            }
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosPraiseWithCosId:(NSInteger)cosId isPraise:(BOOL)isPraise {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_praise" : isPraise ? @(1) : @(0)};
    NSLog(@"点赞的请求%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayPraise] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay点赞返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay点赞失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosCollectWithCosId:(NSInteger)cosId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestHomepageWithHeader:(BOOL)isHeader {
    NSInteger last_id = isHeader ? 0 : self.hpModel.cosplay_list.lastObject.cosplayId;
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(last_id) forKey:@"last_id"];
    [pars setObject:@(kRequestCosplaySize) forKey:@"size"];
    if (self.user_id) {
        [pars setObject:@(self.user_id) forKey:@"user_id"];
    }
    if (self.user_name.length) {
        [pars setObject:self.user_name forKey:@"nick_name"];
    }
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"visitor_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineHomepage] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self homepageWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestEditUserInfoWithHeadImgUrl:(NSString *)headimg_url homepage_img_url:(NSString *)homepage_img_url {
    // 发布Cos需要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    if (headimg_url) {
        [pars setObject:headimg_url forKey:@"headimg_url"];
    }
    if (homepage_img_url) {
        [pars setObject:homepage_img_url forKey:@"homepage_img_url"];
    }
    
    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiModifyMyInfo] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"修改个人信息成功：%@", responseObject);
        [hud hideAnimated:YES];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            if (headimg_url) {
                self.hpModel.user_detail.headimg_url = headimg_url;
            }
            if (homepage_img_url) {
                self.hpModel.user_detail.homepage_img_url = homepage_img_url;
            }
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"修改个人信息失败：%@", error);
        [hud hideAnimated:NO];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
- (void)requestAddBlacklist {
//    // 发布Cos需要登录
//    if (![KABModel sharedInstance].isLogin) {
//        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
//        return;
//    }
//    
//    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
//    
//    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
//    [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
//    [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
//    [pars setObject:@(self.user_id) forKey:@"xxxx"];
//    
//    [[XDAFNetworking sharedInstance] PUT:[ApiManager apiModifyMyInfo] parameters:pars success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
//        NSLog(@"加入黑名单成功：%@", responseObject);
//        [hud hideAnimated:YES];
//        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"添加成功"];
//        } else {
//            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
//        }
//    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        NSLog(@"加入黑名单失败：%@", error);
//        [hud hideAnimated:NO];
//        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
//    }];
}
- (void)requestFollowWithFollowerId:(NSInteger)followerId isFollow:(BOOL)isFollow {
    // 关注必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 关注请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"follower_id" : @(followerId),
                           @"is_follow" : isFollow ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiFollow] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求关注返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            NSString *msg = isFollow ? @"关注成功" : @"已取消关注";
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
            self.hpModel.follow_state = ((self.hpModel.follow_state & 0x02) | isFollow);
            [self refreshWholeView];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求关注失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}
#pragma mark - getters and setters
- (UIBarButtonItem *)skinBarBtnItem {
    if (!_skinBarBtnItem) {
        _skinBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"mine_hp_skin"] style:UIBarButtonItemStylePlain target:self action:@selector(skinBtnTapped:)];
    }
    return _skinBarBtnItem;
}
- (UIBarButtonItem *)followBarBtnItem {
    if (!_followBarBtnItem) {
        _followBarBtnItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"cosplay_praise"] style:UIBarButtonItemStylePlain target:self action:@selector(followBarBtnItemTapped:)];
    }
    return _followBarBtnItem;
}
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
